package com.jlu.springbootjwt.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureGenerationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jlu.springbootjwt.utils.JWTUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HashMap<String, Object> map = new HashMap<>();

    String token = request.getHeader("token");

    try{
      JWTUtil.verrify(token);
      return true;
    }catch (TokenExpiredException e){
      e.printStackTrace();
      map.put("msg:","令牌过期");
    }catch (AlgorithmMismatchException e){
      e.printStackTrace();
      map.put("msg:","算法不匹配");
    }catch (SignatureGenerationException e){
      e.printStackTrace();
      map.put("msg:","签名无效");
    }catch (Exception e){
      e.printStackTrace();
      map.put("msg:","token无效");
    }
    map.put("state:",false);

    String json = new ObjectMapper().writeValueAsString(map);
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().println(json);
    return false;
  }
}
